#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include "bitmap.h"

#define max(a, b) ((a)>(b))?(a):(b)
#define min(a, b) ((a)>(b))?(b):(a)

const int imageWidth = 240;
const int imageHeight = 320;

pixel_t* sourceImage;
pixel_t* referenceImage;

int main(int argc, char** argv) {

	int valid = 1;
	int errorPixels = 0;

	sourceImage = (pixel_t*) malloc(imageWidth * imageHeight * sizeof(pixel_t));
	referenceImage = (pixel_t*) malloc(imageWidth * imageHeight * sizeof(pixel_t));

	// Load the source image from file
	if (!LoadBitmapFile(argv[1], sourceImage, imageWidth, imageHeight)) {
		return -1;
	}

	if(!LoadBitmapFile(argv[2], referenceImage, imageWidth, imageHeight)) {
		return -1;
	}

	// Check pixels
	int i;
	int j;
	
	for (i = 0; i < imageHeight; i++) {
		for (j=0; j < imageWidth; j++){

			int diff_r = abs(sourceImage[i*imageWidth + j].R - referenceImage[i*imageWidth + j].R);
			int diff_g = abs(sourceImage[i*imageWidth + j].G - referenceImage[i*imageWidth + j].G);
			int diff_b = abs(sourceImage[i*imageWidth + j].B - referenceImage[i*imageWidth + j].B);

			if (diff_r > 2 || diff_g > 2 || diff_b > 2) {
				printf("Subpixels that deviate by more than 2!\n");
				valid = 0;
				errorPixels++;
			} else if (diff_r || diff_g || diff_b) {
				errorPixels++;
			}
		}
	}
	
	if (errorPixels > 50) {
		printf("Total number of erroneous pixels is more than 50! (%d)\n", errorPixels);
		valid = 0;
	} else {
		printf("Total number of erroneous pixels is less than 50. (%d)\n", errorPixels);
	}

	if (valid) {
		printf("Result: VALID\n");
	} else {
		printf("Result: INVALID\n");
	}

	free(sourceImage);
	free(referenceImage);

	return 0;
}
